# -*- coding: utf-8 -*-
"""
Author: chen xi
Date: 2025/6/26 下午3:36
File: app.py
"""

from flask import Flask, request, send_from_directory, render_template_string, jsonify
import os

# =============================
# 初始化 Flask 应用
# =============================
app = Flask(__name__)

# =============================
# 配置
# =============================
UPLOAD_FOLDER = 'logs'
ALLOWED_EXTENSIONS = {'zip', 'tar.gz', 'tgz'}  # 支持的压缩文件类型

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 创建日志目录（如果不存在）
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# =============================
# 工具函数
# =============================
def allowed_file(filename):
    if '.' not in filename:
        return False
    ext = filename.rsplit('.', 1)[1].lower()
    return ext in ALLOWED_EXTENSIONS


# =============================
# 页面模板（HTML）
# =============================
INDEX_HTML = '''
<!doctype html>
<html>
<head><title>Compressed Log Upload & Download</title></head>
<body>
    <h1>Upload Compressed Log File (.zip, .tar.gz, .tgz)</h1>
    <form method="post" action="/upload" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload">
    </form>

    <h2>Available Archives:</h2>
    <ul>
        {% for log in logs %}
            <li><a href="/download/{{ log }}">{{ log }}</a></li>
        {% endfor %}
    </ul>
</body>
</html>
'''


# =============================
# 路由定义
# =============================

@app.route('/')
def index():
    logs = os.listdir(app.config['UPLOAD_FOLDER'])
    return render_template_string(INDEX_HTML, logs=logs)


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400
    if file and allowed_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
        return jsonify({
            "message": "File uploaded successfully",
            "filename": file.filename
        }), 200
    else:
        return jsonify({
            "error": "Invalid file type. Only zip/tar.gz/tgz files are allowed."
        }), 400


@app.route('/download/<filename>')
def download_file(filename):
    return send_from_directory(
        app.config['UPLOAD_FOLDER'],
        filename,
        as_attachment=True
    )


# =============================
# 启动服务
# =============================
if __name__ == '__main__':
    print(f"✅ Upload folder: {os.path.abspath(UPLOAD_FOLDER)}")
    app.run(host='0.0.0.0', port=5557, debug=True, threaded=True)